package com.coincalf.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@ServerEndpoint("/websocket/{mobile}")
public class WebSocketServer {

    //记录当前在线连接数
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    //存放每个客户端对应的WebSocketServer对象。
    private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<>(1024);

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //mobile
    private String mobile;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("mobile") String mobile) {
        this.session = session;
        this.mobile = mobile;
        clients.put(mobile, this);
        //TODO 重复连接问题
        WebSocketServer.addOnlineCount();           //在线数加1
        log.info("新用户{}开始连接,当前在线人数为:{}", mobile, getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("{}连接失败，WebSocket IO异常 e={}", mobile, e.getMessage());
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        clients.remove(mobile);
        WebSocketServer.subOnlineCount();           //在线数减1
        log.info("{}连接关闭！当前在线人数为{}", mobile, getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口{}的信息:{}", mobile, message);
        //群发消息
        for (WebSocketServer item : clients.values()) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                log.error("消息发送失败 msg={} mobile={} e={}", message, mobile, e.getMessage());
            }
        }
    }

    /**
     * 连接异常是调用该方法
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.warn("发生错误 e={}", error.getMessage());
    }

    /**
     * 实现服务器主动推送消息
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message, @PathParam("mobile") String mobile) {
        log.info("推送消息到窗口{}推送的消息:{}", mobile, message);
        for (WebSocketServer item : clients.values()) {
            try {
                //如果mobile不为空，则只推送给mobile，否则推送全部
                if (StringUtils.isBlank(mobile)) {
                    item.sendMessage(message);
                } else if (item.mobile.equals(mobile)) {
                    item.sendMessage(message);
                    break;
                }
            } catch (Exception e) {
                log.warn("推送消息到客户端异常 mobile={} msg={}  e={}", mobile, message, e.getMessage());
            }
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendToAll(String message, @PathParam("mobile") String mobile) {
        log.info("推送消息到所有");
        for (WebSocketServer item : clients.values()) {
            try {
                item.sendMessage(message);
            } catch (Exception e) {
                log.warn("推送消息到客户端异常 mobile={} msg={}  e={}", item.mobile, message, e.getMessage());
            }
        }
    }

    public static int getOnlineCount() {
        return onlineCount.get();
    }

    public static void addOnlineCount() {
        WebSocketServer.onlineCount.getAndIncrement();
    }

    public static void subOnlineCount() {
        WebSocketServer.onlineCount.getAndDecrement();
    }

}
